import {
  AbstractNavigator,
  AbstractButton,
  Icon,
  WrappingText,
  ImageTextCard,
  C21Filter,
  Header,
} from "@/components";
import { DISCOVER_TAB_BAR_HEIGHT } from "@/components/c36-TabBarStandalone";
import { useApplicationInfo, getCourses } from "@/store/applicationDataContext";
import { ITouchEvent, View } from "@tarojs/components";
import { useEffect, useLayoutEffect, useMemo, useState } from "react";
import { useDeviceInfo } from "@/store/deviceContext";
import { clamp } from "lodash-es";
import { convertTimeToAmPm, formatDateString } from "@/utils";
import { ApiCourseTypes } from "@/data/courses/courseTypes";
import { ActiveFilterShape } from "../c21-Filter";
import { ActionNames, ActionKeys, sendAction } from "@/utils/tracking";
import { useDidShow } from "@tarojs/taro";
import { DiscoverTabsEnum } from "@/pages/discover/discoverData";
import style from "./index.module.scss";

const FILTER_BAR_HEIGHT_PX = 40;
const SWIPE_CUTOFF = 50;

export default function C04CourseListing() {
  const { applicationState, dispatch } = useApplicationInfo();
  const [showFilter, setShowFilter] = useState(false);
  const [activeFilters, setActiveFilters] = useState<ActiveFilterShape>({
    dateRange: { start: "", end: "" },
    routine_course_category: [],
    routine_course_duration: [],
    routine_course_language: [],
    routine_course_price: [],
  });

  const [tabBarBottom, setTabBarBottom] = useState(0);
  const [contentSpaceHeight, setContentSpaceHeight] = useState(0);
  const [activeCourseIdx, setActiveCourseIdx] = useState(0);
  let touchStartY: null | number = null;

  const { deviceInfoState, navBarBottom } = useDeviceInfo();

  const onCardTouchStart = (event: ITouchEvent) => {
    touchStartY = event.touches[0].clientY;
  };

  const onTouchMove = (event: ITouchEvent) => {
    if (touchStartY !== null) {
      const delta = touchStartY - event.touches[0].clientY;
      if (Math.abs(delta) > SWIPE_CUTOFF) {
        const targetIdx = activeCourseIdx + Math.sign(delta);
        const resultIdx = clamp(
          targetIdx,
          0,
          applicationState.courses.length - 1
        );
        setActiveCourseIdx(resultIdx);
        touchStartY = null;
      }
    }
  };

  useEffect(() => {
    sendAction(ActionNames.CourseImpression);
  }, []);

  useEffect(() => {
    if (!applicationState.courses.length) {
      getCourses(dispatch);
    }
    initSharing();
  }, [dispatch]);

  useDidShow(() => {
    initSharing();
  });

  const initSharing = () => {
    if (dispatch) {
      dispatch({
        type: "DISCOVER_TAB",
        data: {
          tab: DiscoverTabsEnum.Courses,
        },
      });
    }
  };

  // If courses updates -> reset selected course
  useEffect(() => {
    if (applicationState.courses.length) {
      setActiveCourseIdx(0);
    }
  }, [applicationState.courses]);

  // Special non-reusable layout, not moved to usePageDimensions
  useLayoutEffect(() => {
    const calcTabBarBottom = navBarBottom + DISCOVER_TAB_BAR_HEIGHT;
    setTabBarBottom(calcTabBarBottom);

    const { windowHeight } = deviceInfoState;
    setContentSpaceHeight(
      windowHeight - calcTabBarBottom - FILTER_BAR_HEIGHT_PX
    );
  }, [deviceInfoState, navBarBottom]);

  const activeCourse = applicationState.courses.length
    ? applicationState.courses[activeCourseIdx]
    : null;

  const anyActiveFilters = useMemo(() => {
    return (
      activeFilters.dateRange.start ||
      activeFilters.dateRange.end ||
      // If any have values for filter attached
      Object.keys(activeFilters)
        .filter((key) => key !== "dateRange")
        .some((keyExclDate) => activeFilters[keyExclDate].length)
    );
  }, [activeFilters]);

  return (
    <View className={style["course-listing-wrapper"]} onTouchMove={onTouchMove}>
      <View className={style["filter-wrapper"]}>
        <View
          className={style["filter-bar"]}
          style={
            tabBarBottom
              ? {
                top: `${tabBarBottom - 1}px`,
                height: FILTER_BAR_HEIGHT_PX,
              }
              : {}
          }
        >
          <AbstractButton
            variant="plain"
            className={style["filter-button"]}
            onClick={() => {
              sendAction(ActionNames.CourseSelectClick, {});
              setShowFilter(true);
            }}
          >
            <Icon type="Filter" className={style["filter-icon"]} />
            {anyActiveFilters && <View className={style["active-filter"]} />}
          </AbstractButton>
        </View>

        {applicationState.courseFilterParams && (
          <View
            className={`${style["course-filter"]} ${showFilter ? style.visible : null
              }`}
            style={
              tabBarBottom
                ? {
                  top: `${FILTER_BAR_HEIGHT_PX}px`,
                }
                : {}
            }
          >
            <C21Filter
              // Remapping to have same naming
              filterFields={{
                routine_course_category:
                  applicationState.courseFilterParams.routine_course_category.map(
                    (item) => ({
                      id: item.id,
                      asString: item.courseTypeName,
                      status: item.status,
                    })
                  ),
                routine_course_duration:
                  applicationState.courseFilterParams.routine_course_duration.map(
                    (item) => ({
                      id: item.id,
                      asString: item.courseDuration,
                      status: item.status,
                    })
                  ),
                routine_course_language:
                  applicationState.courseFilterParams.routine_course_language
                    .filter(
                      (item) =>
                        item.courseLanguage === "普通话" ||
                        item.courseLanguage === "英语"
                    )
                    .map((item) => ({
                      id: item.id,
                      asString: item.courseLanguage,
                      status: item.status,
                    })),
                routine_course_price:
                  applicationState.courseFilterParams.routine_course_price.map(
                    (item) => ({
                      id: item.id,
                      asString: item.coursePrice,
                      status: item.status,
                    })
                  ),
              }}
              activeFilters={activeFilters}
              activeFilterSetter={setActiveFilters}
              showFilterSetter={setShowFilter}
            />
          </View>
        )}
      </View>

      {anyActiveFilters && !applicationState.courses.length ? (
        // No results due to filtering
        <Header type="heading-n" className={style["no-filter-results"]}>
          暂无匹配结果
        </Header>
      ) : (
        // Regular display content
        <View
          className={style["course-content"]}
          style={{ height: contentSpaceHeight }}
        >
          {/* Course listing column */}
          <View className={style["course-listing"]}>
            {applicationState.courses.map((course, arrayIdx) => {
              return (
                <View
                  onClick={() => {
                    setActiveCourseIdx(arrayIdx);
                    sendAction(ActionNames.CourseLeftButtonClick, {
                      [ActionKeys.CourseLeftButtonName]: course.name,
                    });
                  }}
                  key={`${course.type}-${course.id}`}
                  className={`${style["course-listing--card"]} ${arrayIdx === activeCourseIdx ? style.active : ""
                    }`}
                >
                  <View
                    className={`${style["course-listing--course-highlight"]}`}
                    style={
                      arrayIdx === activeCourseIdx
                        ? { backgroundColor: course.typeLabelColor }
                        : {}
                    }
                  />
                  {/* Non-standard sizing - may need change */}
                  <WrappingText
                    className={`${style["course-listing--card-title"]}`}
                  >
                    {course.name}
                  </WrappingText>
                </View>
              );
            })}
          </View>

          {/* Course card */}
          <View className={style["course-card-area"]}>
            {activeCourse && (
              <AbstractNavigator
                className={style["course-card-wrapper"]}
                url={
                  activeCourse.type === ApiCourseTypes.Single
                    ? `pages/course-detail/index?id=${activeCourse.id}`
                    : `pages/bundlecourse-detail/index?id=${activeCourse.id}`
                }
                onClick={() => {
                  sendAction(ActionNames.CourseContentClick, {
                    [ActionKeys.CourseContentName]: activeCourse.name,
                    [ActionKeys.CourseContentType]: activeCourse.type.toString(),
                  });
                }}
              >
                <ImageTextCard
                  onTouchStart={onCardTouchStart}
                  imagePath={activeCourse.cover}
                  tag={activeCourse.typeName}
                  clickIndication
                  themeColor={activeCourse.typeLabelColor}
                  title={activeCourse.name}
                  cost={Number(activeCourse.price)}
                  date={{
                    date: activeCourse.schedulingDate ? formatDateString(activeCourse.schedulingDate) : '',
                    time: activeCourse.schedulingDate ? `${convertTimeToAmPm(
                      activeCourse.schedulingStartTime
                    )} - ${convertTimeToAmPm(activeCourse.schedulingEndTime)}` : '',
                  }}
                  type="course-card-tall"
                />
              </AbstractNavigator>
            )}
          </View>
        </View>
      )}
    </View>
  );
}
